package com.panfeng.xcloud.common.security.feign;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.panfeng.xcloud.common.core.enums.ResponseStatusEnum;
import com.panfeng.xcloud.common.core.exceptions.BaseBizException;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.HashMap;

/**
 *
 * feign错误拦截器
 *
 * @author xiaobo
 * @version 1.0
 * @since 2018-12-28
 */
@Slf4j
public class FeignOauth2ErrorInterceptor implements ErrorDecoder {

	private final ErrorDecoder defaultErrorDecoder = new Default();

	@Override
	public Exception decode(final String methodKey, final Response response) {
		if (response.status() >= HttpStatus.BAD_REQUEST.value() && response.status() < HttpStatus.INTERNAL_SERVER_ERROR.value()) {
			return new HystrixBadRequestException("request exception wrapper");
		}
		ObjectMapper mapper = new ObjectMapper();
		try {
			HashMap map = mapper.readValue(response.body().asInputStream(), HashMap.class);
			String code = (String) map.get("code");
			String message = (String) map.get("message");
			if (code != null) {
				ResponseStatusEnum anEnum = ResponseStatusEnum.getEnum(code);
				if (anEnum != null) {
					if (anEnum == ResponseStatusEnum.PARAMETER_ERROR) {
						throw new IllegalArgumentException(message);
					} else {
						throw new BaseBizException(anEnum);
					}
				} else {
					throw new BaseBizException(ResponseStatusEnum.UNKNOW_ERROR, message);
				}
			}
		} catch (IOException e) {
			log.info("Failed to process response body");
		}
		return defaultErrorDecoder.decode(methodKey, response);
	}
}
